import {defineStore} from 'pinia'
import {ref,h} from 'vue'
import {ajax,loadComponent as load,user} from 'framework'
import {message,loadingBar} from 'heyui'
import {$t} from 'i18n'
let router
export function setRouter(_router){
    router=_router;
}
export function getRouter(){
    return router
}
let hasHome=false,firstPage='';
const addRoutes = (menus) => {
    for (let menu of menus) {
        if (menu.children) {
            addRoutes(menu.children)
        } else if (menu.path) {
            if(!firstPage){
                firstPage=menu.key
            }
            let path = menu.path;
            if (path.startsWith('url:')) {
                router.addRoute('Index', {
                    name: menu.key,
                    path: menu.key,
                    meta: {
                        title: $t(menu.title,menu.en)
                    },
                    props: {path: menu.path.substr(4)},
                    component: () => load('./coms/iframe.vue')
                })
            } else if (path.startsWith('_blank:')) {
                // menu.nativeLink = true
                // menu.target = "_blank"
                // menu.href = path.substr(7)
                continue
            } else {
                if(menu.key=="Home"){
                    hasHome=true
                }
                let menuPath=menu.key
                let queryIdx = menuPath.indexOf("?")
                if(queryIdx>-1){
                    menuPath=menuPath.substring(0,queryIdx);
                }
                router.addRoute('Index', {
                    name: menu.key,
                    path: menuPath == "Home" ? "/" : menuPath,
                    meta: {
                        title: $t(menu.title,menu.en)
                    },
                    component: () => {
                        return new Promise((resolve,reject) => {
                            loadingBar.start()
                            importShim("./"+menu.path).then(r => {
                                loadingBar.success();
                                resolve(r)
                            }).catch(e => {
                                loadingBar.fail();
                                if (e.status == 404 || e.message == 'Failed to fetch') {
                                    router.push("/404")
                                } else if(e instanceof TypeError && (e.message.startsWith("Unable to fetch")||e.message.startsWith("NetworkError"))){
                                   // router.push("/404")
                                    message({type: 'error', text: '网络异常，请检查网络连接'})
                                } else if(e instanceof SyntaxError){
                                    console.error(menu.path,e)
                                    message({type: 'error', text: '页面解析错误，请打开控制台查看'})
                                } else {
                                    console.error(menu.path,e)
                                    message({type: 'error', text: e.statusText || e.message})
                                }
                                reject(e)
                            })
                        })

                    }
                })

            }
        }
    }
}
export function getUser(){
    return user
}
export function loadUserInfo() {
    return new Promise((resolve, reject) => {
        ajax.get('system/user_info').then(r => {
            if(!r.data){
               // console.log("error")
                reject()
                return
            }else if(r.data.menu&&r.data.menu.length>0){
                addRoutes(r.data.menu)
                if(!hasHome&&firstPage){
                    //添加空白页
                    router.addRoute('Index', {
                        name: 'Home',
                        path: '/',
                        meta: {
                            title: $t('首页','Home')
                        },
                        redirect: firstPage
                    })
                }
            }else{
                //添加空白页
                router.addRoute('Index', {
                    name: 'Home',
                    path: '/',
                    meta: {
                        title: $t('首页','Home')
                    },
                    component: h('div')
                })
            }

            user.value = r.data
            resolve(r)
            if (router.currentRoute.value.name == "Login") {
                router.push('/')
                console.log("to index page")
            }
        }).catch(e => {
            console.error(e)
            reject(e)
        })
    })
}
export const useStore = defineStore('application',()=> {

    const theme = ref()
    const configs = ref(window._configs)
    const title = ref()

    return {
        user,
        theme,
        configs,
        title,
        /** ================== methods =============**/

    }
})
